<script setup lang="ts">
import { toRef, ref, reactive } from 'vue'
import useAppStore from '@/store'
import { onLoad } from '@dcloudio/uni-app'
import { getMemberOrderList, sendGoods, MemberOrderRepurchase, MemberOrderDelete, MemberOrderReceipt } from '@/api/order'
import { OrderListItem } from '@/types/order'
import { userAddressesStore } from '@/store/address'

const appStore = useAppStore()
const safeArea = toRef(appStore, 'safeArea')

// 游标的索引
const swiperIndex = ref<number>(0)
// 调整游标的值
const adjustIndex = ref<number>(0)
// 游标位置
let cursorLeft = $ref<string>('0%')
// 切换订单类型
const changeTab = (ev: WechatMiniprogram.SwiperChange) => {
  // 获取当前选择的订单类型的索引
  swiperIndex.value = ev.target.dataset.index || ev.detail.currentItemId
}

// 显示加载中的提示信息
const showToastLoading = () => uni.showToast({ title: '加载中', icon: 'loading'})

// 游标滑动结束后的回调
const onFinish = async() => {
  // 控制索引值改变的顺序
  adjustIndex.value = swiperIndex.value
  // 显示加载中的提示信息
  showToastLoading()
  // 获取当前订单类型的订单列表
  await changeType()
}

// 游标滑动过程中的回调
const onTransition = (ev: WechatMiniprogram.SwiperTransition) => {
  // 清空订单列表
  orderList.value.length  = 0
  // 获取动画相关参数
  const current = parseInt(ev.target.dataset.current)
  // 获取游标的水平偏移量
  const dx = ev.detail.dx
  // 设置游标的位置
  cursorLeft = (current + dx / safeArea.value!.width) * 20 + '%'
}

// 枚举对象
enum OrderState {
  '待付款' = 1,
  '待发货' = 2,
  '待收货' = 3,
  '待评价' = 4,
  '已完成' = 5,
  '已取消' = 6,
}

// 订单列表
const orderList = ref<OrderListItem[]>([])

// 页面加载时
onLoad(async({ type }) => {
  // 如果有传入订单类型的索引，则使用传入的值
  if(type !== undefined) swiperIndex.value = Number(type)
  // 显示加载中的提示信息
  showToastLoading()
  // 获取当前订单类型的订单列表
  await changeType()
})

// 订单总条数
const total = ref(0)

  // 请求参数
const data = reactive({
  // 当前页数
  page: 1,
  // 每页显示的订单数
  pageSize: 3,
  // 当前订单类型的索引
  type: swiperIndex.value,
})

// 获取当前订单类型的订单列表
const changeType = async() => {
  // 设置订单类型的索引
  data.type = swiperIndex.value
  // 获取订单列表及总订单数
  const { items, counts } = await getMemberOrderList(data)
  // 合并订单
  orderList.value = [...orderList.value, ...items]
  // 设置订单总条数
  total.value = counts
}

// // 订单类型的选项
const itemUrl = [
  { id: 0, text: '全部'},
  { id: 1, text: '待付款'},
  { id: 2, text: '待发货'},
  { id: 3, text: '待收货'},
  { id: 4, text: '待评价'},
]

// 查看物流
const logistics = () => { uni.navigateTo({ url: '/pages/order/logistics' }) }

const changeSend = async(id: string) => {
  // 显示提示信息
  uni.showToast({ title: '已催促卖家尽快发货！' })
  // 调用请求方法
  await sendGoods(id)
}

// 前往支付页
const toPayMent = (id: string) => uni.navigateTo({ url: `/pages/order/detail?id=${id}` })

// 取消订单
const cancel = (State: any) => {
  State = OrderState['已取消']
}

// 查看详情
const orderDetails = async(id: string) => {
  uni.navigateTo({ url: `/pages/order/detail?id=${id}` })
}
// 订单加载状态
const finish = ref(false)

// 下拉触底的事件
const onScrolltolower = () => {
  // 如果已经加载完所有订单，则直接返回
  if(finish.value) return
  // 如果当前订单列表已经加载完所有订单
  if(orderList.value.length === total.value) {
    // 将订单加载状态设置为完成
    finish.value = true
    // 显示提示信息
    return uni.showToast({ title: '订单加载完毕！' })
  }
  // 页数 +1
  data.page++
  // 调用获取当前订单类型的订单列表
  changeType()
}

// 查看订单
const toOrderDetail = (id: string) => uni.navigateTo({ url: `/pages/order/detail?id=${id}` })

// 删除订单
const delOrder = async(id: string) => {
  console.log(id)
  await MemberOrderDelete(id)
}

const addressStore = userAddressesStore()

// 再次购买
const Repurchase = async(id: string) => {
  const res = await MemberOrderRepurchase(id)
  const skuIds = []
  const counts = []
  for(const i of res.goods) {
    skuIds.push(i.skuId)
    counts.push(i.count)
  }
  const addressId = addressStore.selectedAddress.id
  skuIds.join(',')
  counts.join(',')
  uni.navigateTo({
    url: `/pages/order/create/index?skuId=${skuIds}&count=${counts}&addressId=${addressId}`,
  })
}
</script>

<template>
  <view class="viewport">
    <view class="tabs" @tap="changeTab">
      <text :data-index="item.id" v-for="item in itemUrl" :key="item.id">{{ item.text }}</text>
      <!-- 游标 -->
      <view class="cursor" :style="{ left: cursorLeft }"></view>
    </view>
    <swiper class="orders" :data-current="adjustIndex" :duration="200" :current="swiperIndex" @change="changeTab" @animationfinish="onFinish" @transition="onTransition">
      <!-- 全部 -->
      <swiper-item :item-id="indexs.id" v-for="indexs in itemUrl" :key="indexs.id">
        <scroll-view enhanced scroll-y :show-scrollbar="false" @scrolltolower="onScrolltolower">
          <view class="card" v-for="item in orderList" :key="item.id">
            <!-- 订单相关 -->
            <view class="status">
              <text class="date" @tap="toOrderDetail(item.id)">{{ item.createTime }}</text>
              <template v-if="item.orderState === OrderState['待付款']">
                <text class="primary">待付款</text>
              </template>
              <template v-if="item.orderState === OrderState['待发货']">
                <text class="primary">待发货</text>
              </template>
              <template v-if="item.orderState === OrderState['待收货']">
                <text class="primary">待收货</text>
              </template>
              <template v-if="item.orderState === OrderState['已完成']">
                <text>已完成</text>
              </template>
              <template v-if="item.orderState === OrderState['已取消']">
                <text>已取消</text>
              </template>
              <template v-if="item.orderState === OrderState['待评价']">
                <text>待评价</text>
              </template>
              <text v-if="item.orderState !== OrderState['待收货'] && item.orderState !== OrderState['待付款'] && item.orderState !== OrderState['待付款']" class="icon-delete" @tap="delOrder(item.id)"></text>
            </view>
            <!-- 商品信息 -->
            <navigator class="goods" :url="`/pages/goods/index?id=${i.spuId}`" hover-class="none" v-for="i in item.skus" :key="i.id">
              <view class="cover">
                <image :src="i.image" />
                <text class="quantity">x{{ i.quantity }}</text>
              </view>
              <view class="meta">
                <view class="name ellipsis">
                  {{ i.name }}
                </view>
                <view class="type">{{ i.attrsText }}</view>
              </view>
            </navigator>
            <!-- 支付信息 -->
            <view class="payment" @tap="toOrderDetail(item.id)">
              <text class="quantity">共 {{ item.totalNum }} 件商品</text>
              <text>实付</text>
              <text class="amount"> <text class="symbol">¥
              </text>{{ item.totalMoney }}</text>
            </view>
            <!-- 订单操作 -->
            <view class="action" v-if="item.orderState === OrderState['已完成']">
              <view class="button primary" @tap="orderDetails(item.id)">查看订单</view>
              <view class="button primary">再次购买</view>
            </view>
            <view class="action" v-if="item.orderState === OrderState['待付款']">
              <text class="button primary" @tap="toPayMent(item.id)">支付订单</text>
              <view class="button primary" @tap="cancel(item.id)">取消订单</view>
            </view>
            <view class="action" v-if="item.orderState === OrderState['待发货']">
              <view class="button primary" @tap="changeSend(item.id)">催促发货</view>
              <view class="button" @tap="cancel(item.orderState)">取消订单</view>
            </view>
            <view class="action" v-if="item.orderState === OrderState['已取消']">
              <view class="button primary" @tap="Repurchase(item.id)">再次购买</view>
              <view class="button" @tap="orderDetails(item.id)">查看订单</view>
            </view>
            <view class="action" v-if="item.orderState === OrderState['待收货']">
              <view class="button primary" @tap="orderDetails(item.id)">确认收货</view>
              <view class="button" @tap="logistics">查看物流</view>
            </view>
            <view class="action" v-if="item.orderState === OrderState['待评价']">
              <view class="button primary">申请售后</view>
              <view class="button">去评价</view>
            </view>
          </view>
          <view class="loading" v-if="orderList.length < total">正在加载...</view>
          <view class="loading" v-if="finish">~我是有底线的~</view>
        </scroll-view>
      </swiper-item>
    </swiper>
  </view>
</template>

<style>
page {
  height: 100%;
  overflow: hidden;
}

.viewport {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #fff;
}

.tabs {
  display: flex;
  justify-content: space-around;
  line-height: 60rpx;
  margin: 0 10rpx;
  background-color: #fff;
  box-shadow: 0 4rpx 6rpx rgba(240, 240, 240, 0.6);
  position: relative;
  z-index: 9;
}

.tabs text {
  flex: 1;
  text-align: center;
  padding: 20rpx;
  font-size: 28rpx;
  color: #262626;
}

.tabs .cursor {
  position: absolute;
  left: 0;
  bottom: 20rpx;

  display: block;
  content: '';
  width: 20%;
  height: 4rpx;
  padding: 0 50rpx;
  background-clip: content-box;
  background-color: #27ba9b;
}

.orders {
  background-color: #f7f7f8;
}

.orders .card {
  min-height: 100rpx;
  padding: 20rpx;
  margin: 20rpx 20rpx 0;
  border-radius: 10rpx;
  background-color: #fff;
}

.orders .card:last-child {
  padding-bottom: 40rpx;
}

.orders .status {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 28rpx;
  color: #999;
  margin-bottom: 15rpx;
}

.orders .status .date {
  color: #666;
  flex: 1;
}

.orders .status .primary {
  color: #ff9240;
}

.orders .status .icon-delete {
  line-height: 1;
  margin-left: 10rpx;
  padding-left: 10rpx;
  border-left: 1rpx solid #e3e3e3;
}

.orders .goods {
  display: flex;
  margin-bottom: 20rpx;
}

.orders .goods .cover {
  width: 170rpx;
  height: 170rpx;
  margin-right: 20rpx;
  border-radius: 10rpx;
  overflow: hidden;
  position: relative;
}

.orders .goods .quantity {
  position: absolute;
  bottom: 0;
  right: 0;
  line-height: 1;
  padding: 6rpx 4rpx 6rpx 8rpx;
  font-size: 24rpx;
  color: #fff;
  border-radius: 10rpx 0 0 0;
  background-color: rgba(0, 0, 0, 0.6);
}

.orders .goods .meta {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.orders .goods .name {
  height: 80rpx;
  font-size: 26rpx;
  color: #444;
}

.orders .goods .type {
  line-height: 1.8;
  padding: 0 15rpx;
  margin-top: 10rpx;
  font-size: 24rpx;
  align-self: flex-start;
  border-radius: 4rpx;
  color: #888;
  background-color: #f7f7f8;
}

.orders .goods .more {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 22rpx;
  color: #333;
}

.orders .payment {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  line-height: 1;
  padding: 20rpx 0;
  text-align: right;
  color: #999;
  font-size: 28rpx;
  border-bottom: 1rpx solid #eee;
}

.orders .payment .quantity {
  font-size: 24rpx;
  margin-right: 16rpx;
}

.orders .payment .amount {
  color: #444;
  margin-left: 6rpx;
}

.orders .payment .symbol {
  font-size: 20rpx;
}

.orders .action {
  display: flex;
  flex-direction: row-reverse;
  justify-content: flex-start;
  padding-top: 20rpx;
}

.orders .action .button {
  width: 200rpx;
  height: 60rpx;
  text-align: center;
  line-height: 60rpx;
  margin-left: 20rpx;
  border-radius: 60rpx;
  border: 1rpx solid #ccc;
  font-size: 26rpx;
  color: #444;
}

.orders .action .primary {
  color: #27ba9b;
  border-color: #27ba9b;
}

.orders .blank {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  font-size: 30rpx;
  margin-top: -40rpx;
  color: #666;
}
.loading {
  padding: 16px 0;
}
</style>
